import * as cc from "cc";
import yyComponent from "../../Script/Common/yyComponent";
import { EventType } from "../../Script/GameSpecial/GameEventType";

const { ccclass, property } = cc._decorator;
/**加载进度条UI */
@ccclass
export default class LoadingUI extends yyComponent {

    @property(cc.Node)
    protected bar: cc.Node = null;
    protected barTransform: cc.UITransform = null;
    @property
    protected totalLength: number = 0;

    protected preRate: number = 0;
    public init() {
        // return;
        if (this.totalLength == 0) {
            this.totalLength = this.bar.getComponent(cc.Sprite).spriteFrame.originalSize.width;
        }
        this.bar.setPosition(-0.5 * this.totalLength, this.bar.position.y);
        this.barTransform = this.bar.getComponent(cc.UITransform);
        this.barTransform.width = 75;
        this.preRate = 0;
        this.onEvents();
    }

    protected onEvents() {
        this.on(EventType.Common.LoadAssetEvent.showProgress, this.onShowProgress, this);
        this.on(EventType.Common.LoadAssetEvent.updateProgress, this.onUpdateProgress, this);
        this.on(EventType.Common.LoadAssetEvent.hideProgress, this.onHideProgress, this);
    }

    protected onShowProgress(rate: number) {
        this.node.active = true;
        if (undefined === rate) {
            rate = 0;
        }
        if (rate < this.preRate) {
            rate = this.preRate;
        }
        let w = this.totalLength * rate;
        if (w < 1) {
            w = 1;
        }
        this.barTransform.width = w;
        this.preRate = rate;
    }

    protected onUpdateProgress(rate: number) {
        if (rate == 1) {
            this.preRate = 0;
            return;
        }
        if (rate > this.preRate) {
            let w = this.totalLength * rate;
            if (w < 1) {
                w = 1;
            }
            this.barTransform.width = w;
            this.preRate = rate;
        }
    }

    protected onHideProgress() {
        this.node.active = false;
        this.preRate = 0;
    }

}
